#!/usr/bin/env bash
# Copyright (C) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in project root for information.

. "$(dirname "${BASH_SOURCE[0]}")/../../runme"
main() {

show section "Building Docker Image"

_rmcd "$BUILD_ARTIFACTS/docker-work"

_tgzip() { # outdir workdir (always packs ".")
  # avoid tracking times/owners to keep the bits stable (for docker caching)
  local out="$1" dir="$2"; shift 2
  if [[ "$dir" != "$out" ]]; then cp -al "$dir" "$out"; fi
  tar cf - --mtime 1970-1-1T00:00 --owner=mmlspark --group=mmlspark "$out" \
    | gzip -n9 > "$out.tgz"
  rm -rf "$out"
}

local envtgz="$INSTALLER_CACHE_DIR/$(get_runtime_hash).tgz"
if [[ ! -r "$envtgz" ]]; then
  show - "Creating base environment cache"
  _ docker run --interactive --rm \
               -v "$BASEDIR:/mkenv/src:ro" \
               -v "$INSTALLER_CACHE_DIR:/mkenv/cache:ro" \
               -v "$(pwd):/home" \
               ubuntu:16.04 "/mkenv/src/tools/docker/build-env" \
    2>&1 | ( IFS=""; while read -r line; do echo "| $line"; done )
  _ cp -al "mmlspark.tgz" "$envtgz"; rm "mmlspark.tgz"
fi

_ _tgzip "notebooks" "$BUILD_ARTIFACTS/notebooks/local"
_ _tgzip "mml-m2"    "$BUILD_ARTIFACTS/packages/m2"
_ _tgzip "bin"       "$TOOLSDIR/docker/bin"
_ cp "$TOOLSDIR/docker/Dockerfile"* .

find . -type f | xargs cksum > ~/tmp/1

_ docker system prune -f

# plain image
_ cp -al "$envtgz" "mmlspark.tgz"
_ MML_DOCKER_BASE_IMAGE="ubuntu:16.04" \
  MML_DOCKER_TARGET_TAG="mmlspark" \
  docker-buildx -t mmlspark .
# gpu image
_ cp -al "$envtgz" "mmlspark.tgz" # (again since the Dockerfile deletes it)
_ MML_DOCKER_BASE_IMAGE="nvidia/cuda:8.0-cudnn6-runtime-ubuntu16.04" \
  MML_DOCKER_TARGET_TAG="mmlspark-gpu" \
  docker-buildx -t mmlspark-gpu .

_ cd "$BASEDIR"
_rm "$BUILD_ARTIFACTS/docker-work"

}
main "$@"
